import React, { useState } from 'react';
import { Layout, Menu, Breadcrumb, Card, Table, Button, Modal, Form, Input, InputNumber, Select, message, DatePicker } from 'antd';
import { ShoppingCartOutlined, PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import { Content } from 'antd/es/layout/layout';

const { Option } = Select;

const SalesRecord = () => {
  const [salesRecords, setSalesRecords] = useState([
    { id: 1, medicineName: '阿莫西林胶囊', customerName: '张三', quantity: 2, totalPrice: 40, date: '2023-05-15' },
    { id: 2, medicineName: '布洛芬片', customerName: '李四', quantity: 1, totalPrice: 20, date: '2023-05-16' },
    { id: 3, medicineName: '维生素C片', customerName: '王五', quantity: 5, totalPrice: 50, date: '2023-05-17' },
    { id: 4, medicineName: '奥美拉唑', customerName: '赵六', quantity: 1, totalPrice: 40, date: '2023-05-18' },
  ]);
  
  const medicines = [
    { id: 1, name: '阿莫西林胶囊', price: 20 },
    { id: 2, name: '布洛芬片', price: 20 },
    { id: 3, name: '奥美拉唑', price: 40 },
    { id: 4, name: '维生素C片', price: 10 },
  ];
  
  const customers = [
    { id: 1, name: '张三' },
    { id: 2, name: '李四' },
    { id: 3, name: '王五' },
    { id: 4, name: '赵六' },
  ];

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  // 表格列定义
  const columns = [
    {
      title: '药品名称',
      dataIndex: 'medicineName',
      key: 'medicineName',
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '总价(元)',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
    },
    {
      title: '销售日期',
      dataIndex: 'date',
      key: 'date',
    },
  ];

  const showModal = () => {
    form.resetFields();
    // 设置默认日期为今天
    form.setFieldsValue({ date: moment() });
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      const selectedMedicine = medicines.find(m => m.id === values.medicineId);
      if (!selectedMedicine) return;
      
      const totalPrice = selectedMedicine.price * values.quantity;
      
      const newRecord = {
        id: salesRecords.length > 0 ? Math.max(...salesRecords.map(r => r.id)) + 1 : 1,
        medicineName: selectedMedicine.name,
        customerName: customers.find(c => c.id === values.customerId)?.name || '',
        quantity: values.quantity,
        totalPrice: totalPrice,
        date: values.date.format('YYYY-MM-DD')
      };
      
      setSalesRecords([newRecord, ...salesRecords]);
      message.success('销售记录添加成功！');
      form.resetFields();
      setIsModalVisible(false);
    });
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
  };

  // 当药品或数量改变时，自动计算总价
  const onValuesChange = (changedValues: any, allValues: any) => {
    if ((changedValues.medicineId !== undefined || changedValues.quantity !== undefined) && 
        allValues.medicineId && allValues.quantity) {
      const selectedMedicine = medicines.find(m => m.id === allValues.medicineId);
      if (selectedMedicine) {
        const totalPrice = selectedMedicine.price * allValues.quantity;
        form.setFieldsValue({ totalPrice });
      }
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Layout className="site-layout">
        <Content style={{ margin: '16px' }}>
          <Breadcrumb style={{ margin: '16px 0' }}>
            <Breadcrumb.Item>销售记录</Breadcrumb.Item>
          </Breadcrumb>
          <div className="site-layout-background" style={{ padding: 24, minHeight: 360, background: '#fff' }}>
            <Card 
              title="销售记录" 
              bordered={false}
              extra={
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={showModal}
                >
                  添加销售记录
                </Button>
              }
            >
              <Table dataSource={salesRecords} columns={columns} pagination={{ pageSize: 5 }} />
            </Card>
          </div>
        </Content>
      </Layout>

      {/* 添加销售记录模态框 */}
      <Modal
        title="添加销售记录"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form form={form} layout="vertical" onValuesChange={onValuesChange}>
          <Form.Item
            name="medicineId"
            label="药品"
            rules={[{ required: true, message: '请选择药品!' }]}
          >
            <Select placeholder="请选择药品">
              {medicines.map(medicine => (
                <Option key={medicine.id} value={medicine.id}>{medicine.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="customerId"
            label="客户"
            rules={[{ required: true, message: '请选择客户!' }]}
          >
            <Select placeholder="请选择客户">
              {customers.map(customer => (
                <Option key={customer.id} value={customer.id}>{customer.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="quantity"
            label="数量"
            rules={[{ required: true, message: '请输入数量!' }]}
          >
            <InputNumber min={1} step={1} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="totalPrice"
            label="总价(元)"
          >
            <InputNumber disabled style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="date"
            label="销售日期"
            rules={[{ required: true, message: '请选择销售日期!' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default SalesRecord;